﻿using System;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Threading;
using zTalk.Network;

namespace zTalk
{
    public partial class Register : Window
    {
        private volatile bool inited = false;

        public Register()
        {
            InitializeComponent();

            App.Handler.Register += new PacketEventHandler(Handler_Register);
        }

        void Handler_Register(object sender, PacketEventArgs ea)
        {
            if ((bool)ea.Result == true)
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                    if (inited == false)
                    {
                        inited = true;
                        Login l = new Login();
                        l.InitFields(txtUsername.Text, txtPassword.Password);
                        l.Show();
                        Close();
                    }
                }));
            }
            else
            {
                triggerLoading(false);
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                    lblErrors.Content = "! Username is already in use. Try different one";
                    errorPane.Visibility = Visibility.Visible;
                }));
            }
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                triggerLoading(true);

                if (App.Client.Running == false)
                {
                    App.Client.Start();
                }

                if (txtUsername.Text.Length < 3 || txtUsername.Text.Length > 20)
                {
                    throw new Exception("! Username have to be between 3 and 20 characters");
                }
                if (Regex.IsMatch(txtUsername.Text, @"^[0-9a-zA-z_]+$") == false)
                {
                    throw new Exception("! Invalid characters in username");
                }
                if (txtPassword.Password != txtPassword2.Password)
                {
                    throw new Exception("! Password and confirm password don't match");
                }
                if (txtPassword.Password.Length < 3 || txtPassword.Password.Length > 20)
                {
                    throw new Exception("! Password have to be between 3 and 20 characters");
                }

                Packet packet = Packet.Create(
                    Opcodes.REGISTER,
                    Json.Encode<string[]>(new string[] { txtUsername.Text, App.Sha1(txtPassword.Password) })
                );
                App.Client.SendPacket(packet);
            }
            catch (SocketException)
            {
                triggerLoading(false);
                lblErrors.Content = "! Cannot connect to server";
                errorPane.Visibility = Visibility.Visible;
            }
            catch (Exception exc)
            {
                triggerLoading(false);
                lblErrors.Content = exc.Message;
                errorPane.Visibility = Visibility.Visible;
            }
        }

        private void triggerLoading(bool start)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                btnOk.Content = (start == true) ? "Processing" : "Sign up";
                btnOk.IsEnabled = (start != true);
            }));
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtUsername.Focus();
        }
    }
}
